package com.cn.kehong.controller;


import com.cn.kehong.api.IDepartmentService;
import com.cn.kehong.api.IPersonnelManageService;
import com.cn.kehong.api.IRoleService;
import com.cn.kehong.api.ITerminalLicenseService;
import com.cn.kehong.dao.PersonnelManagementMapper;
import com.cn.kehong.dao.TerminalLicenseMapper;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.cn.kehong.utils.JsonResponse;
import com.cn.kehong.utils.QueryForm;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created On : 2023/12/12.
 * <p>
 * Author : Huiyan
 * <p>
 * Description: 终端许可
 */
@Controller
@RequestMapping("/terminalLicense")
public class TerminalLicenseController {

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private PersonnelManagementMapper personnelManagementMapper;

    @Autowired
    private ITerminalLicenseService terminalLicenseService;

    @Autowired
    private TerminalLicenseMapper terminalLicenseMapper;


    @RequestMapping("/getTerminalLicenselList/{frontToken}")
    @ResponseBody
    public JsonResponse<List<TerminalLicense>> getTerminalLicenselList(@RequestBody QueryForm queryForm, @PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<List<TerminalLicense>> response = new JsonResponse<>();
        List<TerminalLicense> terminalLicenses = terminalLicenseService.getTerminalLicenselList(queryForm);
        response.setResult(terminalLicenses);
        response.setSuccess(true);
        return response;
    }

    //新增接口
    @RequestMapping("/addTerminalLicense/{frontToken}")
    @ResponseBody
    public JsonResponse<String> addTerminalLicense(@RequestBody List<TerminalLicense> terminalLicense,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<String> response = new JsonResponse<>();
        String result = terminalLicenseService.addTerminalLicense(terminalLicense);
        return CommonUtil.getResponseData(response,result);
    }




    //删除接口
    @RequestMapping("/deleteTerminalLicense/{frontToken}")
    @ResponseBody
    public JsonResponse<String> deleteTerminalLicense(@RequestBody QueryForm queryForm,@PathVariable(value = "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<String> response = new JsonResponse<>();
        String result = terminalLicenseService.deleteTerminalLicense(queryForm);
        return CommonUtil.getResponseData(response,result);
    }


    //修改接口
    @RequestMapping("/updateTerminalLicense/{frontToken}")
    @ResponseBody
    public JsonResponse<String> updateTerminalLicense(@RequestBody TerminalLicense terminalLicense, @PathVariable(value =  "frontToken",required = true) String frontToken) throws Exception{
        JsonResponse<String> response = new JsonResponse<>();
        String result = terminalLicenseService.updateTerminalLicense(terminalLicense);
        return CommonUtil.getResponseData(response,result);
    }

    // 数量
    @RequestMapping("/getTerminalLicenseCount")
    @ResponseBody
    public JsonResponse<Map<String, Object>> getTerminalLicenseCount() throws Exception {
        JsonResponse<Map<String, Object>> response = new JsonResponse<Map<String, Object>>();
        Map<String, Object> terminalLicenseCount = terminalLicenseService.getTerminalLicenseCount();
        response.setResult(terminalLicenseCount);
        response.setSuccess(true);
        return response;
    }


    //终端许可模版下载
    @ResponseBody
    @RequestMapping("/downloadTerminalLicense")
    public void downloadPersonTempFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/");
        String fileName = path + "terminalLicense.xlsx";
        this.downloadFile(fileName,response);
    }
    public void downloadFile(String path, HttpServletResponse response) throws Exception {
        String name = StringUtils.isNotBlank(path)?path:"";
        name = URLDecoder.decode(name,"utf-8");
        name = new String(name.getBytes("ISO-8859-1"),"utf-8");
        InputStream is = null;
        OutputStream os = null;
        try {
            File file = new File(name);
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            is = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            closeInputStream(is);
            closeOutputStream(os);
        }
    }

    private static void closeInputStream(InputStream is) {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void closeOutputStream(OutputStream os) {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //终端许可模版导入
    @ResponseBody
    @RequestMapping("/importTerminalLicense")
    public JsonResponse<String> importTerminalLicense(@RequestParam(value = "multipartFile", required = true) MultipartFile multipartFile, @RequestParam(value ="notToken", required = true) String notToken) throws Exception {
        JsonResponse<String> response = new JsonResponse<String>();
        DataFormatter formatter = new DataFormatter();

        try{
            InputStream is=multipartFile.getInputStream();
            XSSFWorkbook wb=new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0); // 获取第一个工作表
            XSSFRow row=null;
            XSSFCell cell=null;
            List<TerminalLicense> terminalLicenseList=new ArrayList<>();
            int num=1;
            for (int i=1;i<=sheet.getLastRowNum();i++){
                row=sheet.getRow(i);
                TerminalLicense terminalLicense = new TerminalLicense();
                String id = CommonUtil.generateRandomNum("terminalLicense_");
                terminalLicense.setId(id);
                terminalLicense.setStatus("0");
                terminalLicense.setXkStatus("1");
                terminalLicense.setCreateTime(new Date());
                terminalLicense.setUpdateTime(new Date());
                for (int j=0;j<row.getLastCellNum();j++){
                    cell=row.getCell(j);
                    String cellValue = formatter.formatCellValue(cell);
                    if (j==0){
                        List<Department> department=departmentService.getIdBydeptName(cellValue);
                        if (department.size()==0){
                            response.setMessage("第"+num+"行"+"部门不存在，请检查部门");
                            return response;
                        }else {
                            terminalLicense.setDeptId(department.get(0).getId());
                        }
                    }else if (j==1){
                        terminalLicense.setEmployeeName(cellValue);
                    }else if(j==2){
                        terminalLicense.setNumber(cellValue);
                    }else if(j==3){
                        terminalLicense.setTerminalAme(cellValue);
                        terminalLicense.setCreateBy("admin");
                    }
                    else if(j==4){
                        if (this.countEqName(cellValue,id) > 0){
                            response.setMessage("第"+num+"行"+"Mac地址已经存在，请检查Mac地址");
                            return response;
                        }else {
                            terminalLicense.setMacAddress(cellValue);
                        }
                    }
                }
                terminalLicenseList.add(terminalLicense);
                num++;
            }
            int ret = terminalLicenseMapper.batchInser(terminalLicenseList);
            if (ret!=0){
                response.setSuccess(true);
                return response;
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setMessage("系统忙，请稍后重试....");
        }
        return response;
    }

    private int countEqName(String name,String id) {
        TerminalLicenseExample terminalLicenseExample = new TerminalLicenseExample();
        terminalLicenseExample.createCriteria().andStatusNotEqualTo(Constants.DEL_STATUS).andMacAddressEqualTo(name);
        int count = terminalLicenseMapper.countByExample(terminalLicenseExample);
        return count;
    }


}
